package com.example.shop.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.example.common.service.ImageManage;
import com.example.common.utils.MinioUtils;
import com.example.shop.entity.Goods;
import com.example.shop.entity.GoodsImage;
import com.example.shop.entity.GoodsSku;
import com.example.shop.entity.Shop;
import com.example.shop.mapper.GoodsImageMapper;
import com.example.shop.mapper.GoodsMapper;
import com.example.shop.mapper.GoodsSkuMapper;
import com.example.shop.mapper.ShopMapper;
import com.example.shop.model.req.AddGoodsDTO;
import com.example.shop.model.req.AddSkusDTO;
import com.example.shop.model.req.GoodsDTO;
import com.example.shop.model.req.GoodsSkuDTO;
import com.example.shop.model.resp.GoodsDetail;
import com.example.shop.model.resp.GoodsList;
import com.example.shop.model.resp.SaleAttrs;
import com.example.shop.model.resp.ShopDetail;
import com.example.shop.service.GoodsImageService;
import com.example.shop.service.GoodsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.IntStream;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/9/2 22:49
 **/
@Service
@RequiredArgsConstructor
public class GoodsServiceImpl implements GoodsService {
    private final GoodsMapper goodsMapper;
    private final GoodsImageMapper goodsImageMapper;
    private final GoodsImageService goodsImageService;
    private final GoodsSkuMapper goodsSkuMapper;
    private final ImageManage imageManage;
    private final ShopMapper shopMapper;
    private final MinioUtils minioUtils;

    @Override
    public void saveGoods(AddGoodsDTO addGoodsDTO) {
        String goodsId = UUID.randomUUID().toString();
        Goods goods = Goods.builder().goodsId(goodsId).title(addGoodsDTO.getTitle()).coverImageId(addGoodsDTO.getBannerUrl().get(0)).categoryId(addGoodsDTO.getCategoryId()).saleTime(addGoodsDTO.getSaleTime()).price(addGoodsDTO.getPrice()).build();
        goodsMapper.addGoods(goods);

        List<GoodsImage> goodsBannerImages = IntStream.range(0, addGoodsDTO.getBannerUrl().size()).mapToObj(i -> GoodsImage.builder().goodsId(goodsId).fileId(addGoodsDTO.getBannerUrl().get(i)).type("banner").orderNum(i).build()).toList();

        List<GoodsImage> goodsInfoImages = IntStream.range(0, addGoodsDTO.getInfoUrl().size()).mapToObj(i -> GoodsImage.builder().goodsId(goodsId).fileId(addGoodsDTO.getInfoUrl().get(i)).type("info").orderNum(i).build()).toList();

        goodsImageMapper.batchInsertGoodsImages(goodsBannerImages);
        goodsImageMapper.batchInsertGoodsImages(goodsInfoImages);

        List<AddSkusDTO> addSkusDTOS = addGoodsDTO.getSkus();
        if (addSkusDTOS != null) {
            for (AddSkusDTO addSkusDTO : addSkusDTOS) {
                GoodsSku goodsSku = GoodsSku.builder().goodsId(goodsId).skuId(UUID.randomUUID().toString()).attr(addSkusDTO.getAttr()).coverImageId(addSkusDTO.getSkuUrl()).build();
                goodsSkuMapper.saveGoodsSku(goodsSku);
            }
        }
    }

    @Override
    public GoodsDetail getGoodsDetail(String goodsId) {
        GoodsDetail goodsDetail = new GoodsDetail();

        // 查询goodsId是否存在
        Goods goods = goodsMapper.queryGoodsById(goodsId);
        Assert.notNull(goods, "查询商品为空");
        goodsDetail.setGoodsId(goodsId);
        goodsDetail.setTitle(goods.getTitle());
        goodsDetail.setPrice(goods.getPrice());
        goodsDetail.setMarketPrice(goods.getMarketPrice());
//        goodsDetail.setStatus(goods.());
//        goodsDetail.setHaveSku(goods.isHaveSku());
        goodsDetail.setSaleTime(goods.getSaleTime());
        goodsDetail.setTags(Collections.singletonList(goods.getTagType()));

        // 查询商品sku
        List<GoodsSku> goodsSkus = goodsSkuMapper.queryGoodsSkuByGoodsId(goodsId);
        SaleAttrs saleAttrs = SaleAttrs.builder().name("款式").isOpen(false).key(goodsId).build();
        List<SaleAttrs.SkuInfo> skuInfos = new ArrayList<>();
        for (GoodsSku skus : goodsSkus) {
            SaleAttrs.SkuInfo skuInfo = SaleAttrs.SkuInfo.builder().isChose(true).key(skus.getSkuId()).text(skus.getAttr()).imgUrl(imageManage.getImageUrl(skus.getCoverImageId())).build();
            skuInfos.add(skuInfo);
        }
        saleAttrs.setContent(skuInfos);
        goodsDetail.setSaleAttrs(Collections.singletonList(saleAttrs));

        // 查询店铺
//        shopMapper.queryShopById(goods.getShopId)
        Shop shop = shopMapper.queryShopById( goods.getShopId() != null ? goods.getShopId() : "xqtd");
        goodsDetail.setShop(ShopDetail.builder().official(true).shopCode(shop.getShopId()).shopName(shop.getShopName()).icon("https://mock-url").cert(true).build());

        // 查询展示主图
        List<String> goodsImages = goodsImageService.queryGoodsImages(goods.getGoodsId(), "banner");
        goodsDetail.setMainImage(goodsImages.get(0));
        goodsDetail.setImages(goodsImages);

        // 查询详情图
        List<String> goodsDetailImages = goodsImageService.queryGoodsImages(goods.getGoodsId(), "info");
        goodsDetail.setDetailImages(goodsDetailImages);

        return goodsDetail;
    }

    @Override
    public List<GoodsList> getGoodsList() {
        List<Goods> goods = goodsMapper.queryGoodsList();
        return goods.stream()
                .map(good -> GoodsList.builder()
                        .id(good.getGoodsId())
                        .title(good.getTitle())
                        .price(good.getPrice())
                        .image(imageManage.getImageUrl(good.getCoverImageId()))
                        .tagType(good.getTagType())
                        .build())
                .toList();
    }

    @Override
    @Transactional
    public void saveGoods(GoodsDTO goodsDTO) {
        String goodsId = UUID.randomUUID().toString();
        // 处理首页图片和详情图片
        List<GoodsImage> goodsImages = uploadImage(goodsId, goodsDTO.getImages(), "banner");
        List<GoodsImage> detailImages = uploadImage(goodsId, goodsDTO.getDetailImages(), "info");

        // 处理商品基础信息
        Goods goods = Goods.builder().goodsId(goodsId)
                .title(goodsDTO.getTitle())
                .shopId(goodsDTO.getShopCode() == null ? "xqtd" : goodsDTO.getShopCode())
                .categoryId(goodsDTO.getCategory())
                .stock(goodsDTO.getStock())
                .tagType( goodsDTO.getTags() != null ? goodsDTO.getTags().get(0) : null)
                .saleTime(goodsDTO.getSaleTime())
                .coverImageId(goodsImages.get(0).getFileId())
                .price(goodsDTO.getPrice())
                .marketPrice(goodsDTO.getMarketPrice())
                .build();

        goodsMapper.addGoods(goods);

        goodsImageMapper.batchInsertGoodsImages(goodsImages);
        goodsImageMapper.batchInsertGoodsImages(detailImages);

        // 处理子商品
        List<GoodsSkuDTO> saleAttrs = goodsDTO.getSaleAttrs();
        if (saleAttrs != null) {
            for (GoodsSkuDTO saleAttr : saleAttrs) {
                List<GoodsSkuDTO.SkuDTO> skuDTOS = saleAttr.getContent();
                for (GoodsSkuDTO.SkuDTO skuDTO : skuDTOS) {
                    String fileId = skuDTO.getImgUrl();
                    GoodsSku goodsSku = GoodsSku.builder()
                            .skuId(skuDTO.getKey())
                            .goodsId(goodsId)
                            .attr(skuDTO.getText())
                            .coverImageId(fileId)
                            .build();
                    goodsSkuMapper.saveGoodsSku(goodsSku);
                }
            }
        }
    }

    public List<GoodsImage> uploadImage(String goodsId, List<String> base64Images, String type) {
        List<GoodsImage> goodsImages = new ArrayList<>();
        int index = 0;
        for (String fileId : base64Images) {
//            String fileId = minioUtils.uploadBese64(image);
            GoodsImage images = GoodsImage.builder()
                    .fileId(fileId)
                    .goodsId(goodsId)
                    .orderNum(index)
                    .type(type)
                    .build();
            index++;
            goodsImages.add(images);
        }
        return goodsImages;
    }
}
